<template> 
  <MenuPage>
    <template slot="search">
      <Input
        v-model.trim="currentQueryObj.name"
        clearable
        placeholder="输入名称查询"
        :maxlength="20"
        style="width: 180px;margin-left: 15px;float:right"
        @on-change="filterAchor"
      />
      <Input
        v-model.trim="currentQueryObj.content"
        clearable
        placeholder="输入内容查询"
        :maxlength="20"
        style="width: 180px;margin-left: 15px;float:right"
        @on-change="filterAchor"
      />
    </template>
    <template slot="content">
      <Tabs value="exp" @on-click="changeTabs" class="hp100 flex-column">
        <TabPane label="课件" name="exp" class="achor">
          <TableList
            :columns="videoCol"
            :data="dataList"
            :span-method="handleSpan"
            :loading="tableLoading"
            :total="total"
            :page.sync="currentQueryObj.pageIndex"
            :size.sync="currentQueryObj.pageSize"
            @queryFun="queryListByType"
          ></TableList>
        </TabPane>
        <TabPane label="专业课程" name="course" class="achor">
          <TableList
              :columns="videoCol"
              :data="dataList"
              :span-method="handleSpan"
              :loading="tableLoading"
              :total="total"
              :page.sync="currentQueryObj.pageIndex"
              :size.sync="currentQueryObj.pageSize"
              @queryFun="queryListByType"
          ></TableList>
          <!-- <Row style="text-align:center;padding:15px;justify-content:center" v-if="total">
            <Page
              :total="total"
              :current="currentQueryObj.pageIndex"
              :page-size="currentQueryObj.pageSize"
              show-elevator
              show-total
              @on-change="changePage"
            />
          </Row> -->
        </TabPane>
        <TabPane label="视频" name="video" class="achor" v-if="false">
          <TableList
            :columns="videoCol"
            :data="dataList"
            :span-method="handleSpan"
            :loading="tableLoading"
            :total="total"
            :page.sync="currentQueryObj.pageIndex"
            :size.sync="currentQueryObj.pageSize"
            @queryFun="queryListByType"
          ></TableList>
          <!-- <Table
            :columns="videoCol"
            :data="dataList"
            :max-height="setTableHei"
            :span-method="handleSpan"
            :loading="tableLoading"
          ></Table>
          <Row style="text-align:center;padding:15px;justify-content:center" v-if="total">
            <Page
              :total="total"
              :current="currentQueryObj.pageIndex"
              :page-size="currentQueryObj.pageSize"
              show-elevator
              show-total
              @on-change="changePage"
            />
          </Row> -->
        </TabPane>
      </Tabs>
    </template>
    <Modal
      v-model="achorModal"
      :title="currentTitle"
      :mask-closable="false"
      :footer-hide="true"
      :width="800"
    >
      <p style="color:#999;text-align: right;margin-bottom: 16px;">{{ currentTime }}</p>
      <quill-editor
        v-model="currentTotalContent"
        class="editor"
        ref="myQuillEditor"
        :options="editorOption"
      >
      </quill-editor>
    </Modal>
  </MenuPage>
</template>
<script>
import usally from '@/mixin/usally';
import { queryStudyVideo } from '@/api/videoSelfStudy.js'; //视频
import { getExpList, getcourselist, getNotesList } from '@/api/selfStudy/courseExp.js'; //课件
import { queryAchorNote } from '@/api/selfStudy/courseExp.js';
import moment from 'moment';
import { Base64 } from 'js-base64';
import Quill from 'quill';
import { quillEditor } from 'vue-quill-editor'; // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { debounce } from '@/libs/utils';
export default {
  mixins: [usally],
  components: {
    quillEditor
  },
  data() {
    const validateName = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_-]*$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入中文、数字、字母、下划线、-'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //			let September = sessionStorage.getItem('November')
    //			September = JSON.parse(encryption.SelfUseDecrypt(September))
    return {
      //				USER_ID: September.userId,
      //				USER_Name: September.nickname,
      //				isRootDesigner: September.isRootDesigner,
      currentType: 1, //1.课程, 2.课件, 3.视频
      setTableHei: 0,
      currentTotalContent: '',
      achorModal: false,
      total: 0,
      showDefImg: true,
      showExpDefImg: true,
      showCourseDefImg: true,
      showDefText: '加载中',
      currentTitle: '',
      editorOption: {
        modules: {
          toolbar: false
        }
      },
      currentQueryObj: {
        pageIndex: 1,
        pageSize: 10,
        name: '',
        content: ''
      },
      tableLoading: true,
      
      dataList: [],
      currentTime: '',
      recordTotal: 0,
      compositeScoreCol: [
        {
          title: '排行',
          width: 60,
          key:'rank',
          align: 'center',
          render: (h, params) => {
            return h(
              'span',
              this.compositeScore.pageSize * (this.compositeScore.pageIndex - 1) +
                (params.row._index + 1)
            );
          }
        },
        {
          title: '用户名',
          key: 'username',
          align: 'center',
          tooltip: true,
          placement: 'top-left',
          width: 200
        },
        {
          title: '昵称',
          key: 'nickname',
          align: 'center',
          tooltip: true,
          width: 200
        },
        {
          title: '综合评分',
          key: 'totalScore',
          align: 'center',
          tooltip: true,
          width: 200
        },
        {
          title: '操作',
          width: 100,
          placement: 'top-right',
          action: true,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  style: {
                    background: 'none',
                    border: 'none',
                    boxShadow: 'none'
                  },
                  on: {
                    click: () => {
                      sessionStorage.setItem('queryObj', this.queryObj);
                      this.$router.push({
                        name: 'staticticsDetail',
                        query: {
                          id: params.row.id,
                          name: params.row.nickname
                        }
                      });
                    }
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: require('../../assets/project/magnifier-h.png'),
                      title: '查看学习详情'
                    },
                    style: {
                      cursor: 'pointer',
                      'margin-right': '5px',
                      'vertical-align': 'middle',
                      //width:'16px',
                      //height:'16px',
                      display: 'inline-block'
                    }
                  }),
                  h('span', {
                    style: {
                      cursor: 'pointer',
                      color: '#2f70ff'
                    }
                  })
                ]
              )
            ]);
          }
        }
      ],
      compositeScoreList: [], //试卷列表
      compositeScoreTotal: 0 //排行总数
    };
  },
  computed: {
    pageTitle () {
      //当前菜单显示名
      return this.$store.getters.pageTitle;
    },
    videoCol(){
      return  [
        {
          title: '名称',
          key: 'showname',
          tooltip: true
        },
        {
          title: '类型',
          key:'experimentType',
          show:this.currentType==2,
          render: (h, params) => {
            let experimentType = params.row.experimentType
            let map ={
              0:'实操课件',
              1:'理论课件',
              2:'文本课件'
            }
            return h('div', {},map[experimentType])
          }
        },
          
        {
          title: '锚定人',
          key: 'userName',
          tooltip: true
        },
        {
          title: '最新锚定时间',
          key: 'lastTime',
          tooltip: true
        },
        {
          title: '详细内容',
          key:'singerAllList',
          render: (h, params) => {
            return params.row.singerAllList
                ? h('div', [
                  h(
                      'Button',
                      {
                        props: {
                          type: 'primary',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px'
                        },
                        on: {
                          click: () => {
                            this.preContent(params.row);
                          }
                        }
                      },
                      '查看详情'
                  )
                ])
                : h('div', '-');
          }
        }
      ]
    }
  },
  filters: {},
  watch: {},
  methods: {
    // 设置高度
    setStyle: debounce(function() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 280;
      let tableHei = this.fullHeight - 150;
      this.currentQueryObj.pageSize = Math.floor(tableHei / 50);
      if (this.total > this.currentQueryObj.pageSize) {
        let maxPage = Math.ceil(this.total / this.currentQueryObj.pageSize);
        if (maxPage < this.currentQueryObj.pageIndex) {
          this.currentQueryObj.pageIndex = maxPage;
        }
      }
      this.queryListByType();
    }, 500),
    refreshCompositeScoreList() {
      this.compositeScore.userName = '';
      this.compositeScore.nickName = '';
      this.changePage(1);
    },
    handlerLastTime(d) {
      if (d.length) {
        let arr = d.map((item) => new Date(item.updateTime || item.createTime).getTime());
        return moment(Math.max(...arr)).format('YYYY-MM-DD HH:mm:ss');
      } else {
        return '-';
      }
    },
    preContent(d) {
      this.currentTitle = d.showname;
      this.currentTime = d.lastTime;
      this.currentTotalContent = this.handlerAllTotal(d.singerAllList);
      this.achorModal = true;
    },
    handlerAllTotal(d) {
      let content = d.reduce((pre, cur) => {
        let note = Base64.decode(cur.content);
        try {
          cur.handlerContent = JSON.parse(note).noteContent;
        } catch (err) {
          cur.handlerContent = note;
        }
        pre += `<h3>${cur.title}</h3>${cur.handlerContent}`;
        return pre;
      }, '');
      return content;
    },
    changeTabs(name) {
      this.showDefImg = true;
      this.currentQueryObj.name = '';
      this.currentQueryObj.content = '';
      this.currentQueryObj.pageIndex = 1;
      switch (
        name //1.课程, 2.课件, 3.视频
      ) {
        case 'video':
          this.currentType = 3;
          break;
        case 'exp':
          this.currentType = 2;
          break;
        case 'course':
          this.currentType = 1;
          break;
        default:
          break;
      }
      this.queryListByType();
    },
    queryListByType() {
      //查询课程，课件，视频列表
      let _this = this;
      _this.dataList = [];
      _this.total = 0;
      _this.showDefImg = true;
      _this.tableLoading = true;
      //1:视频 2：课件 3：课程
      let params = { ..._this.currentQueryObj };
      params.anchorType = _this.currentType;
      //查询条件存储
      queryAchorNote(params)
        .then((data) => {
          if (data.code === 1) {
            const datas = data.data.items;
            _this.recordTotal = data.data.total;
            if (datas.length <= 0) {
              _this.showDefImg = true;
              _this.showDefText = '暂无信息';
            } else {
            }
            return datas;
          } else {
            _this.showDefImg = true;
            _this.showDefText = '暂无信息';
            _this.$Message.error(data.message);
            _this.dataList = [];
            _this.total = 0;
          }
        })
        .then((r) => {
          let noteList = [];
          const mapType = {
            1: 'course',
            2: 'experiment',
            3: 'video'
          };
          const label = mapType[_this.currentType];
          r.forEach((item) => {
            noteList.push({
              showname: item[`${label}Name`],
              showid: item[`${label}Id`],
              experimentType:item.experimentType,
              list: item.anchors
            });
          });
          return noteList;
        })
        .then((notes) => {
          _this.showDefImg = false;
          let arr = [];
          notes.forEach((item, index) => {
            let joinIndex = notes.slice(0, index).reduce((p, c) => {
              let len = c.list.length ? c.list.length : 1;
              p += len;
              return p;
            }, 0);
            if (item.list.length) {
              item.list.forEach((l) => {
                let joinSpan = item.list.length;
                let lastTime = _this.handlerLastTime(l.notes);
                l = { ...l, singerAllList: l.notes, ...item, joinIndex, joinSpan, lastTime }; //只取joinIndex和rowIndex相等的值合并
                arr.push(l);
              });
            } else {
              let l = {};
              l.joinIndex = joinIndex;
              l.joinSpan = 1;
              l = { ...l, ...item, lastTime: '-', userName: '-' };
              arr.push(l);
            }
          });
          _this.dataList = arr;
          _this.total = _this.recordTotal;
          _this.tableLoading = false;
          console.log('ddddddd', _this.dataList);
        })
        .catch((error) => {
          console.log(error);
          _this.dataList = [];
          _this.total = 0;
        });
    },
    handleSpan({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === row.joinIndex && columnIndex === 0) {
        return {
          rowspan: row.joinSpan,
          colspan: 1
        };
      } else if (
        rowIndex > row.joinIndex &&
        rowIndex < row.joinIndex + row.joinSpan &&
        columnIndex === 0
      ) {
        return {
          rowspan: 0,
          colspan: 0
        };
      }
    },
    changePage: debounce(function(val) {
      this.currentQueryObj.pageIndex = val;
      this.queryListByType();
    }, 500),
    filterAchor: debounce(function() {
      this.currentQueryObj.pageIndex = 1;
      this.queryListByType();
    })
  },
  mounted() {
    //赋值查询条件
    // 	let queryObj = sessionStorage.getItem('queryObj');
    // 	if(queryObj){
    // 		let params = JSON.parse(queryObj);
    // this.compositeScore = params;
    // 		sessionStorage.removeItem("queryObj");
    // 	}
    //this.queryListByType()
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    this.queryListByType();
  },
  beforeDestroy() {
    window.onresize = null;
  },
  created() {}
};
</script>
<style scoped>
  .flex-column{
    display: flex;
    flex-direction: column;
  }
  .flex-column /deep/ .ivu-tabs-content{
    flex:auto
  }
</style>